package com.shengyo.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;



/**
 * 创建SessionFactory工具�?
 * @author Administrator
 *
 */
public class HibernateUtils {

	/*private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	
	private static Configuration cfg = new Configuration();
	
	private static SessionFactory factory;
	
	//只做�?��初始�?
	static {
		
		try{
			
			cfg.configure();
			
			factory = cfg.buildSessionFactory();
		}catch(Exception e){
			System.err.println("****创建SessionFactory失败****");
			e.printStackTrace();
		}
	}
	
	private  HibernateUtils() {}
	
	//取得sessionFactory
	public static SessionFactory getSessionFactory(){
		
		return factory;
	}
	//取得session
	public static Session getSession() throws HibernateException{
		
		Session session = (Session)threadLocal.get();
		
		if (null == session || !session.isOpen()){
			if (null == factory){
				rebuildSessionFactory();
			}
			session = (null != factory) ? factory.openSession(): null;
		}
		return session;
	}
	//创建sessionFactory
	public static void rebuildSessionFactory(){
		
		try{
            cfg.configure();
			
			factory = cfg.buildSessionFactory();
		}catch(Exception e){
			System.err.println("****创建SessionFactory失败****");
			e.printStackTrace();
		}
	}
	//关闭session
	public static void closeSession() throws HibernateException{
		
		Session session = (Session)threadLocal.get();
		
		threadLocal.set(null);
		
		if (null != session){
			if (session.isOpen()){
				session.close();
			}
		}
	}
*/
	private static SessionFactory factory;
	//只初始化�?��
	static {
		try{
			Configuration cfg = new Configuration().configure();
			factory = cfg.buildSessionFactory();
		}catch(Exception e){
			e.printStackTrace();
		}		
	}
	public static SessionFactory getSessionFactory(){
		return factory;
	}
	public static Session getSession(){
		return factory.openSession();
	}
	public static void closeSession(Session session){
		if (session != null){
			if (session.isOpen()){
				session.close();
			}
		}
	}
}
